package main

import (
	"errors"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"net/http"
	"path"
	"strings"
	"time"
	//"ioutil"
)

type ProductType struct {
	Id   int `gorm:"primary_key:id"`
	Name string
	//ProductList []*Product `orm:"reverse(many)"`
}

type Product struct {
	Id     int `gorm:"primary_key:id"`
	Name   string
	Type   ProductType `gorm:"ForeignKey:TypeId;AssociationForeignKey:Id"`
	TypeId int
	//MealList []*Meal `orm:"reverse(many)"`
}

type ProjectType struct {
	Id   int `gorm:"primary_key:id"`
	Name string
	//ProjectList []*Project `orm:"reverse(many)"`
}

type Project struct {
	Id     int `gorm:"primary_key:id"`
	Name   string
	Type   ProjectType `gorm:"ForeignKey:TypeId;AssociationForeignKey:Id"`
	TypeId int
	//MealList []*Meal `orm:"reverse(many)"`
}

type Meal struct {
	Id          int `gorm:"primary_key:id"`
	Name        string
	ProjectList []*Project `gorm:"many2many:meal_projects;"`
	ProductList []*Product `gorm:"many2many:meal_products;"`
	//Memberlist []*Member `orm:"reverse(many)"`
}

type Member struct {
	Id       int `gorm:"primary_key:id"`
	Name     string
	Meallist []*Meal `gorm:"many2many:member_meals;"`
}

// MyClaims 自定义声明结构体并内嵌jwt.StandardClaims
// jwt包自带的jwt.StandardClaims只包含了官方字段
// 我们这里需要额外记录一个username字段，所以要自定义结构体
// 如果想要保存更多信息，都可以添加到这个结构体中
type MemberClaims struct {
	Username string `json:"username"`
	jwt.StandardClaims
}

type UserInfo struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

const TokenExpireDuration = time.Hour * 2

var MemberSecret = []byte("你值得拥有")

// GenToken 生成JWT
func GenToken(username string) (string, error) {
	// priKeyBytes, err := ioutil.ReadFile("./pem/private.pem")
	// if err != nil {
	// 	fmt.Println("私钥文件读取失败")
	// }

	// priKey, err := jwt.ParseRSAPrivateKeyFromPEM(priKeyBytes)
	// if err != nil {
	// 	fmt.Println("私钥文件不正确")
	// }

	// 创建一个我们自己的声明
	c := MemberClaims{
		username, // 自定义字段
		jwt.StandardClaims{
			ExpiresAt: time.Now().Add(TokenExpireDuration).Unix(), // 过期时间
			Issuer:    "member-project",                           // 签发人
		},
	}
	// 使用指定的签名方法创建签名对象
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
	// 使用指定的secret签名并获得完整的编码后的字符串token
	return token.SignedString(MemberSecret)

	//token := jwt.NewWithClaims(jwt.SigningMethodRS256, c)
	//return token.SignedString(priKey)
}

// ParseToken 解析JWT
func ParseToken(tokenString string) (*MemberClaims, error) {

	// pubKeyBytes, err := ioutil.ReadFile("./pem/public.pem")
	// if err != nil {
	// 	fmt.Println("公钥文件读取失败")
	// }

	// pubKey, err := jwt.ParseRSAPublicKeyFromPEM()(pubKeyBytes)
	// if err != nil {
	// 	fmt.Println("公钥文件不正确")
	// }

	// 解析token
	// token, err := jwt.ParseWithClaims(tokenString, &MemberClaims{}, func(token *jwt.Token) (i interface{}, err error) {
	// 	return pubKey, nil
	// })

	token, err := jwt.ParseWithClaims(tokenString, &MemberClaims{}, func(token *jwt.Token) (i interface{}, err error) {
		return MemberSecret, nil
	})
	if err != nil {
		return nil, err
	}
	if claims, ok := token.Claims.(*MemberClaims); ok && token.Valid { // 校验token
		return claims, nil
	} else if ve, ok := err.(jwt.ValidationError); ok {
		if ve.Errors&jwt.ValidationErrorMalformed != 0 {
			fmt.Println("错误的token")
		} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
			fmt.Println(" token过期或未启用")
		} else {
			fmt.Println("Could not handle this token:", err)
		}
	} else {
		fmt.Println("无法解析此token", err)
	}

	return nil, errors.New("invalid token")
}

func authHandler(c *gin.Context) {
	// 用户发送用户名和密码过来
	var user UserInfo
	err := c.ShouldBind(&user)
	fmt.Println(user)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 2001,
			"msg":  "无效的参数",
		})
		return
	}

	// 校验用户名和密码是否正确
	if user.Username == "yangliang" && user.Password == "yangliang123" {
		// 生成Token
		tokenString, _ := GenToken(user.Username)
		c.JSON(http.StatusOK, gin.H{
			"code": 2000,
			"msg":  "success",
			"data": gin.H{"token": tokenString},
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 2002,
		"msg":  "鉴权失败",
	})
	return
}

// JWTAuthMiddleware 基于JWT的认证中间件
func JWTAuthMiddleware() func(c *gin.Context) {
	return func(c *gin.Context) {
		// 客户端携带Token有三种方式 1.放在请求头 2.放在请求体 3.放在URI
		// 这里假设Token放在Header的Authorization中，并使用Bearer开头
		// 这里的具体实现方式要依据你的实际业务情况决定

		//url传递token
		//authHeader := c.Query("token")
		//if authHeader == "" {
		//	c.JSON(http.StatusOK, gin.H{
		//		"code": 2003,
		//		"msg":  "请求头中auth为空",
		//	})
		//	c.Abort()
		//	return
		//}

		//from传递token
		// authHeader := c.PostForm("token")
		// if authHeader == "" {
		// 	c.JSON(http.StatusOK, gin.H{
		// 		"code": 2003,
		// 		"msg":  "请求头中auth为空",
		// 	})
		// 	c.Abort()
		// 	return
		// }

		//请求头传递token
		authHeader := c.Request.Header.Get("token")
		if authHeader == "" {
			c.JSON(http.StatusOK, gin.H{
				"code": 2003,
				"msg":  "请求头中auth为空",
			})
			c.Abort()
			return
		}

		// 按空格分割
		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "SuperToken") {
			c.JSON(http.StatusOK, gin.H{
				"code": 2004,
				"msg":  "请求头中auth格式有误",
			})
			c.Abort()
			return
		}

		// parts[1]是获取到的tokenString，我们使用之前定义好的解析JWT的函数来解析它
		mc, err := ParseToken(parts[1])
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 2005,
				"msg":  "无效的Token",
			})
			c.Abort()
			return
		}

		// 将当前请求的username信息保存到请求的上下文c上
		c.Set("username", mc.Username)
		c.Next() // 后续的处理函数可以用过c.Get("username")来获取当前请求的用户信息
	}
}

func Cors() gin.HandlerFunc {
	return func(context *gin.Context) {
		method := context.Request.Method
		context.Header("Access-Control-Allow-Origin", "*")
		context.Header("Access-Control-Allow-Headers", "Origin, Content-Type,AccessToken,X-CSRF-Token, Authorization, Token, token")
		context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
		context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		context.Header("Access-Control-Allow-Credentials", "false")
		if method == "OPTIONS" {
			context.AbortWithStatus(http.StatusNoContent)
		}
		context.Next()
	}
}

func main() {
	db, err := gorm.Open("mysql", "root:new_password@tcp(localhost:3306)/micro_iris_insert")
	if err != nil {
		panic("failed to connect database")
	}
	defer db.Close()

	db.AutoMigrate(&ProductType{}, &Product{}, &ProjectType{}, &Project{}, &Meal{}, &Member{})

	router := gin.Default()

	router.Use(Cors())

	router.POST("/login", authHandler)
	router.GET("/query", JWTAuthMiddleware(), func(c *gin.Context) {
		var m []*Member
		db.Find(&m)

		// var me []Meal
		// db.Joins("JOIN member_meals ON member_meals.meal_id = meals.id AND member_meals.member_id = ?", 1).Find(&me)
		// fmt.Println(me)

		for _, v := range m {
			db.Joins("JOIN member_meals ON member_meals.meal_id = meals.id AND member_meals.member_id = ?", v.Id).Find(&v.Meallist)
			fmt.Println(v.Meallist)
			for _, mv := range v.Meallist {
				db.Joins("JOIN meal_projects ON meal_projects.project_id = projects.id AND meal_projects.meal_id = ?", mv.Id).Find(&mv.ProjectList)
				fmt.Println(mv.ProjectList)
				for _, jv := range mv.ProjectList {
					db.Joins("JOIN projects ON project_types.id = projects.type_id AND projects.id = ?", jv.Id).Find(&jv.Type)
					fmt.Println(jv.Type)
				}

				db.Joins("JOIN meal_products ON meal_products.product_id = products.id AND meal_products.meal_id = ?", mv.Id).Find(&mv.ProductList)
				fmt.Println(mv.ProductList)
				for _, dv := range mv.ProductList {
					db.Joins("JOIN products ON product_types.id = products.type_id AND products.id = ?", dv.Id).Find(&dv.Type)
					fmt.Println(dv.Type)
				}
			}
		}

		c.JSON(http.StatusOK, m)
	})

	router.GET("/download", func(c *gin.Context) {

		filePath := "F:/hot_change/android/98e536200ff4465a110a86103a02249f.apk"
		//fileTmp, _ := os.Open(filePath)
		//defer fileTmp.Close()

		//获取文件的名称
		fileName := path.Base(filePath)
		//if common.IsEmpty(filePath) || common.IsEmpty(fileName) || errByOpenFile != nil {
		//	logs.Error("获取文件失败")
		//	c.Redirect(http.StatusFound, "/404")
		//	return
		//}
		c.Header("Content-Type", "application/octet-stream")
		//强制浏览器下载
		c.Header("Content-Disposition", "attachment; filename="+fileName)
		//浏览器下载或预览
		c.Header("Content-Disposition", "inline;filename="+fileName)
		c.Header("Content-Transfer-Encoding", "binary")
		c.Header("Cache-Control", "no-cache")

		c.File(filePath)
	})

	router.Run(":9119")

	//fmt.Println(m)

}
